/**
 * 审批按钮组
*/
// import Item from "antd/lib/list/Item";
import "./approveButtonList.css";
import { Spin, Tooltip, message, Modal} from "antd";
import { useRequest, useUpdate } from "ahooks";
import cloneDeep from 'lodash/cloneDeep'
import React, { Suspense, useEffect, useRef, useState } from "react";
import clsx from "clsx";
import request from "../../framework/common/utils/request";
import mysoftMessage from "../../framework/common/utils/message";

import { useForm } from "../../framework/common/context/metadata-context";
import eventBus, { useSubscribe } from "../../framework/common/eventBus";
/**
 * loading 表单数据获取中 true/false
 * toggleFooter 父组件方法，用于发起时，控制表单内容显示隐藏
 */
export default function ({ 
    btnClick,
    className,
    btnListLoading=false
}) {

    const { data: tplData, urlPrefix, params} = useForm().root;

    return <div className="approve_btn_wrap">
                <div className="approve_btn approve_btn_bar">
                    <ButtonList
                        btnListLoading={btnListLoading}
                        btnClick={btnClick}
                        className={className}
                    ></ButtonList>
                </div>
                <ExpandButtonList expandButtonList={tplData?.ExpandButtons}></ExpandButtonList>
            </div>
}

//业务按钮列表
function ButtonList({
    btnClick,
    className,
    approveType,
    btnListLoading
}){
    const { data: tplData, urlPrefix, params} = useForm().root;

    //刷新按钮列表
    let updater = useUpdate();
    useSubscribe("setConsultRead.update", ()=>{
        updater();
    })

    //如果有未读的协商，就会右上角显示小红点，优先显示再回复协商上面
    let unreadOperationCode="";
    if(tplData.NodeInfo?.consults_unread){
        if(tplData.ApproveButtons?.find(a=>a.OperationCode==="ReplyConsult")){
            unreadOperationCode="ReplyConsult"
        }
        else if(tplData.ApproveButtons?.find(a=>a.OperationCode==="Consult")){
            unreadOperationCode="Consult"
        }
    }
    return <div className={clsx("foot_btn_wrap", className)}>
                <Spin spinning={btnListLoading}>
                    <ul className="mb-0">
                        {
                            tplData.ApproveButtons.map(function(item, i){
                                let isActive = "";
                                if(item.OperationCode == 'Initiate' && !params.isSubProc || item.OperationCode === approveType){
                                    isActive = "active";
                                }
                                return <li 
                                            onClick={()=>{
                                                btnClick?.({
                                                    approveType: item.OperationCode,
                                                    text: item.ButtonName
                                                });//更新父组件的当前选中审批类型
                                            }}
                                            className={clsx(isActive,unreadOperationCode===item.OperationCode?"unread_tag":"")} 
                                            key={item.OperationCode}
                                            data-code={item.OperationCode}
                                        >
                                            <i className={clsx("iconfont", item.ButtonIcon)}></i> 
                                            {item.ButtonName}
                                            <div className={clsx("arrows_wrap", item.OperationCode == 'Initiate' && "up")}>
                                                <span className="after"></span>
                                                <span className="before"></span>
                                            </div>
                                        </li>
                            })
                        }
                    </ul>
            </Spin>
        </div>
}
export {ButtonList}

//扩展按钮列表
function ExpandButtonList({
    expandButtonList//扩展按钮列表
}){

    const [expandBtnLoading, setExpandBtnLoading] = useState(false);//按钮loading状态
    useSubscribe("expandBtnLoading.update", (data)=>{
        setExpandBtnLoading(data);
    }, []);//更新扩展按钮的加载状态

    const { data: tplData, params, csrfToken} = useForm().root;
    if(!expandButtonList || expandButtonList?.length <=0){//没有扩展按钮
        return null;
    }
    
    var expandButtons = cloneDeep(expandButtonList);//需要渲染的扩展按钮列表
    let maxButtonNum = 2;//最多显示的按钮数量

    return <>
                <div className="expand_btn approve_btn_bar">
                <Spin spinning={expandBtnLoading}>
                    <ul className="foot_expand_wrap">
                        {
                            expandButtons.map(function(button, index){
                                if((index+1) > maxButtonNum ){//只渲染最多2个按钮
                                    return null;
                                }
                                return <li className="expandHoverItem"
                                            key={button.code}
                                            data-code={button.code}
                                            data-name={button.name}
                                            data-id={button.id}
                                            data-attrs={button.attrs}
                                            data-expand_mode={button.expand_mode}
                                            data-remark={button.remark}
                                            onClick={()=>{
                                                handleClick_ExpandButton({
                                                    button: button,
                                                    tplData: tplData,
                                                    params: params,
                                                    csrfToken: csrfToken
                                                });
                                            }}
                                        >
                                            {button.name}
                                        </li>
                            })
                        }
                    {
                        expandButtons.length > maxButtonNum
                        && <Tooltip 
                            overlayClassName="expand_btn_tip"
                            getPopupContainer={() => document.querySelector(".foot_expand_wrap")} 
                            color="white"
                            placement="bottom"
                            title={
                                <Spin spinning={expandBtnLoading}>
                                    <ExpandMoreButtonList 
                                        buttonList={expandButtons}
                                        maxButtonNum={maxButtonNum}
                                    ></ExpandMoreButtonList>
                                </Spin>
                            }
                        >
                            <li className="more-btn">
                                <i className="iconfont icon-gengduo"></i>
                            </li>
                        </Tooltip>
                            
                    }
                    </ul>
                </Spin>
                </div>
                <Modal_ExpandButton></Modal_ExpandButton>
            </>
}

//扩展按钮更多列表
function ExpandMoreButtonList({
    buttonList,//按钮列表
    maxButtonNum,//正常列表最多显示的数量
    modeInfo
}){
    const { data: tplData, params, csrfToken} = useForm().root;
    return <>
        {
            buttonList.map(function(button, index){
                if(( index + 1 ) <= maxButtonNum){//前两个按钮不显示
                    return null;
                }
                return <span className="inline-block w-32 px-3 leading-9 cursor-pointer expandHoverItem" 
                            onClick={()=>{
                                handleClick_ExpandButton({
                                    button: button,
                                    tplData: tplData,
                                    params: params,
                                    csrfToken: csrfToken,
                                    modeInfo: modeInfo
                                });
                            }}
                            data-code={button.code}
                            key={button.code}
                            data-name={button.name}
                            data-id={button.id}
                            data-attrs={button.attrs}
                            data-expand_mode={button.expand_mode}
                            data-remark={button.remark}
                        >
                            {button.name}
                        </span>
            })
        }
    </>
}

//扩展按钮点击后的弹出框
function saveLog({
    errmsg,
    status,
    params,
    button,
    path,
    StartDate
}) {
    var time_diff = (new Date().getTime()-  StartDate.getTime())/1000;
    request({
        url: '/flowdefine/flow-expand-button/save-expand-button-log',
        method: 'POST',
        data: {
            package_id: params.proc_id,
            process_instance_id: params.package_id,
            auditor_id: params.auditor_id,
            button_id: button.id,
            path: path,
            status: status,
            message: errmsg,
            time_diff: time_diff.toFixed(2)
        }
    });
};
function Modal_ExpandButton({
    
}){
    const [modalInfo, setModalInfo]= useState({
        showModal: false//弹框显示状态
    })

    useSubscribe("setModalInfo.update", (data)=>{
        setModalInfo({...modalInfo, ...data});//更新当前弹出框
    })

    return <Modal 
                title={modalInfo.title}
                centered={true}
                visible={modalInfo.showModal}
                width={modalInfo.width}
                wrapClassName={modalInfo.skin}
                onOk={()=>{
                    setModalInfo(
                        {
                            showModal: false
                        }
                    )
                    // var StartDate = new Date();
                    // var time =  setTimeout(function(){
                    //     saveLog({
                    //         errmsg: '调用业务系统超时',
                    //         status: 0,
                    //         params: modeInfo.params,
                    //         button: modeInfo.button,
                    //         path: modalInfo.url,
                    //         StartDate: StartDate
                    //     })
                    //     // var $frm = layero.find('iframe');
                    //     // frmEl = layero.find('iframe')[0];
                    //     // $frm.attr('onload', null);
                    //     // if (frmEl.src) {
                    //     //     frmEl.src = 'about:blank';
                    //     // }
                    //     // $frm.remove();
                    //     //超时后移除iframe
                    // },30000)
                    
                    // var $cf = $("#form-runtime");
                    // $cf.checkThirdRequired(
                    //     function() {
                    //         clearTimeout(time)
                    //         saveLog({
                    //             errmsg: "调用成功",
                    //             status: 1,
                    //             params: modeInfo.params,
                    //             button: modeInfo.button,
                    //             path: modalInfo.url,
                    //             StartDate: StartDate
                    //         })
                    //     }, 
                    //     function(errmsg) {
                    //         clearTimeout(time);
                    //         if (errmsg) {   
                    //             mysoftMessage.info({
                    //                 content: errmsg
                    //             })
                    //         }
                    //         saveLog({
                    //             errmsg: errmsg || '调用业务系统失败',
                    //             status: 0,
                    //             params: modeInfo.params,
                    //             button: modeInfo.button,
                    //             path: modalInfo.url,
                    //             StartDate: StartDate
                    //         })
                    //     }
                    // );
                }}
                onCancel={()=>{
                    setModalInfo(
                        {
                            showModal: false
                        }
                    )
                }}
            >
                <div style={{
                    "width": "100%",
                    "height": modalInfo.height
                }}>
                    <iframe
                        width="100%"
                        height="100%"
                        src={modalInfo.url}
                        id={modalInfo.id}
                    ></iframe>
                </div>
            </Modal>
}

//扩展按钮点击事件
function handleClick_ExpandButton({
    button,
    tplData,
    params,
    csrfToken
}){

    let attrs = button.attrs;
    if(typeof attrs === "string" ){
        attrs = JSON.parse(attrs);//这个属性要格式化为json
    }
    eventBus.publish("expandBtnLoading.update", true);//扩展按钮loading中
    if(button.expand_mode==0){
        var param = {
            userGuid: tplData.CurUserGUID,
            businessGuid: params.business_id,
            ProccessInstanceID: params.proc_id,
            id: button.id,
            packageID: params.package_id,
            externalApiPath: attrs.external_api_path,
            businessData: {
                main: tplData.form.form_data.main,
                children: tplData.form.form_data.children
            }
        }
        request({
            loading: true,
            url: '/flowdefine/flow-expand-button/trigger-expand-event',
            method: 'POST',
            data: param,
            headers: {
                'X-CSRF-Token': csrfToken
            }
        }).then(function(result){
            if (result.code == 1) {
                message.success("调用成功");
            }
            eventBus.publish("expandBtnLoading.update", false);//扩展按钮loading取消
        },function(){
            mysoftMessage.info({
                content: "调用接口失败"
            });
            eventBus.publish("expandBtnLoading.update", false);//扩展按钮loading取消
        });
    }else{
        var param = {
            url: attrs.package_url,
            proc_id: params.proc_id,
            id: button.id,
            packageID: params.package_id,
        }
        request({
            url: '/flowdefine/flow-expand-button/expand-button-business-url',
            method: 'POST',
            data: param,headers: {
                'X-CSRF-Token': csrfToken
            }
        }).then(function(result){
            if (result.code == 1) {

                eventBus.publish("setModalInfo.update", {
                    showModal: true,//显示弹出框
                    title: button.name,
                    scrollbar: false,
                    id:"expand_iframe",
                    url: result.data.url,
                    width: attrs.size.mode == "auto" ? "98%" : attrs.size.width + "px",
                    height: attrs.size.mode == "auto" ? "70vh" : attrs.size.height + "px",
                    button: button,
                    params: params
                });//更新按钮信息

            }
            eventBus.publish("expandBtnLoading.update", false);//扩展按钮loading取消
        },function(result){
            eventBus.publish("expandBtnLoading.update", false);//扩展按钮loading取消
            mysoftMessage.info({
                content: result.message || "调用接口失败"
            });
        });
    }
}